import { defineStore } from 'pinia'
import { ref } from 'vue'
import { appointmentAPI, applicationAPI } from '@/services/api'

export const useAppointmentsStore = defineStore('appointments', () => {
  const appointments = ref([])
  const currentAppointment = ref(null)
  const loading = ref(false)
  const error = ref('')
  const pagination = ref({
    page: 1,
    limit: 10,
    total: 0,
    pages: 0
  })

  // 获取预约列表
  const fetchAppointments = async (params = {}) => {
    loading.value = true
    error.value = ''

    try {
      const response = await appointmentAPI.getList(params)

      if (response.success !== false) {
        appointments.value = response.data || response
        if (response.pagination) {
          pagination.value = response.pagination
        }
        return { success: true, data: response.data || response }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '获取预约列表失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  // 获取预约详情
  const fetchAppointmentById = async (id) => {
    loading.value = true
    error.value = ''

    try {
      const response = await appointmentAPI.getById(id)

      if (response.success !== false) {
        currentAppointment.value = response.data || response
        return { success: true, data: response.data || response }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '获取预约详情失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  // 创建预约
  const createAppointment = async (appointmentData) => {
    loading.value = true
    error.value = ''

    try {
      const response = await appointmentAPI.create(appointmentData)

      if (response.success !== false) {
        // 添加到本地列表
        appointments.value.unshift(response.data || response)
        return { success: true, message: '预约创建成功', data: response.data || response }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '创建预约失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  // 申请加入预约
  const applyToAppointment = async (appointmentId, reason) => {
    loading.value = true
    error.value = ''

    try {
      const response = await applicationAPI.create({
        appointment_id: appointmentId,
        reason
      })

      if (response.success !== false) {
        return { success: true, message: '申请已提交', data: response.data || response }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '申请失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  // 处理申请（通过或拒绝）
  const processApplication = async (applicationId, status, adminNotes = '') => {
    loading.value = true
    error.value = ''

    try {
      const response = await applicationAPI.processApplication(applicationId, {
        status,
        admin_notes: adminNotes
      })

      if (response.success !== false) {
        // 刷新当前预约信息
        if (currentAppointment.value) {
          await fetchAppointmentById(currentAppointment.value.id)
        }
        return { success: true, message: response.message || '处理成功', data: response.data || response }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '处理申请失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  // 更新预约
  const updateAppointment = async (appointmentId, appointmentData) => {
    loading.value = true
    error.value = ''

    try {
      const response = await appointmentAPI.update(appointmentId, appointmentData)

      if (response.success !== false) {
        // 更新本地数据
        const index = appointments.value.findIndex(a => a.id === appointmentId)
        if (index !== -1) {
          appointments.value[index] = response.data || response
        }
        if (currentAppointment.value && currentAppointment.value.id === appointmentId) {
          currentAppointment.value = response.data || response
        }
        return { success: true, message: '预约更新成功', data: response.data || response }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '更新预约失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  // 删除预约
  const deleteAppointment = async (appointmentId) => {
    loading.value = true
    error.value = ''

    try {
      const response = await appointmentAPI.delete(appointmentId)

      if (response.success !== false) {
        // 从本地列表中移除
        const index = appointments.value.findIndex(a => a.id === appointmentId)
        if (index !== -1) {
          appointments.value.splice(index, 1)
        }
        return { success: true, message: '预约删除成功' }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '删除预约失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  // 退出预约
  const leaveAppointment = async (appointmentId) => {
    loading.value = true
    error.value = ''

    try {
      const response = await appointmentAPI.leaveAppointment(appointmentId)

      if (response.success !== false) {
        // 刷新预约信息
        await fetchAppointmentById(appointmentId)
        return { success: true, message: '已退出预约' }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '退出预约失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  return {
    appointments,
    currentAppointment,
    loading,
    error,
    pagination,
    fetchAppointments,
    fetchAppointmentById,
    createAppointment,
    updateAppointment,
    deleteAppointment,
    applyToAppointment,
    processApplication,
    leaveAppointment
  }
})
